﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;
using System.IO;

public partial class Manager_PriceList_PriceList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BindData();
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        ExportExcel();
    }
    private void ExportExcel()
    {
        StreamWriter writer = null;
        FileStream outputfile = null;
        try
        {
            string DocFileName = "ListFilm-" + System.DateTime.Now.ToString("ddMMyyyyhhmmss");
            string FilePathName = "D:\\MyWeb\\HNB\\HNB\\Database\\PriceList\\" + DocFileName;
            try
            {
                File.Delete(FilePathName);
            }
            catch { }

            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            this.tblMaster.RenderControl(hw);
            string HtmlInfo = tw.ToString().Trim();

            outputfile = new FileStream(FilePathName, FileMode.Create, FileAccess.Write);
            writer = new StreamWriter(outputfile, System.Text.Encoding.GetEncoding("utf-8"));
            writer.BaseStream.Seek(0, SeekOrigin.End);
            outputfile.Flush();
            writer.WriteLine(HtmlInfo);
            writer.Flush();
            writer.Close();


        }
        catch (Exception)
        {


        }
    }

    private void exportold()
    {


        /*this.tblMaster.Page.EnableViewState = false;
                StringWriter tw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(tw);
                this.tblMaster.RenderControl(hw);
                string HtmlInfo = tw.ToString().Trim();


                string DocFileName = "BangBaoGia(HNB)_" + System.DateTime.Now.ToString("dd-MM-yyyy") + ".xls";
                string FilePathName = "";

                FilePathName = "D:\\MyWeb\\HNB\\HNB\\Database\\PriceList\\" + DocFileName;
                try
                {
                    File.Delete(FilePathName);
                }
                catch { }
                FileStream Fs = new FileStream(FilePathName, FileMode.Create);
                System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
                BinaryWriter BWriter = new BinaryWriter(Fs, utf8);

                BWriter.Write(HtmlInfo);
                BWriter.Close();
                Fs.Close();
         * */

        #region Excel
        tblMaster.EnableViewState = false;
        //  ' Set the content type to Excel.
        Response.Clear();
        Response.Buffer = true;
        //Response.ContentEncoding = System.Text.UnicodeEncoding.UTF8;
        Response.Charset = "utf-8";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");

        Response.AppendHeader("Content-disposition", "attachment;filename=BangBaoGia(HNB)_" + System.DateTime.Now.ToString("dd/MM/yyyy") + ".xls");
        Response.ContentType = "application/vnd.ms-excel";// "application/x-msexcel";
        // 'Turn off the view state.
        //this.EnableViewState = false;

        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        hw.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\" \nxmlns=\"http://www.w3.org/TR/REC-html40\">");
        hw.WriteFullBeginTag("HEAD");
        hw.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
        string CSS_PhysicalPath = ResolveUrl("~/") + "Pub/Css/ExportStyles.css";

        if (CSS_PhysicalPath != null)
        {
            hw.RenderBeginTag(HtmlTextWriterTag.Style);
            hw.Write("<!--");

            StreamReader sr = File.OpenText(Server.MapPath(CSS_PhysicalPath));
            String input;
            while ((input = sr.ReadLine()) != null)
            {
                hw.WriteLine(input);
            }
            sr.Close();
            hw.Write("-->");
            hw.RenderEndTag();
        }

        hw.WriteEndTag("HEAD");
        hw.WriteFullBeginTag("BODY");

        hw.WriteEndTag("HEAD");
        hw.WriteFullBeginTag("BODY");


        tblMaster.RenderControl(hw);
        hw.WriteEndTag("BODY");
        hw.WriteEndTag("HTML");
        Response.Write(tw.ToString());
        Response.Flush();
        Response.End();
        #endregion
    }
    private void BindData()
    {
        AddHeader();
        AddRow();
    }

    private void AddHeader()
    {
        PccMsg Msg;
        Msg = new PccMsg();
        Msg.CreateFirstNode("Css", "tbl_trHeader");
        TableRow row;
        TableCell cell;
        row = new TableRow();

        cell = new TableCell();
        cell.Width = Unit.Percentage(3);
        AddCellTextToRow(row, cell, "STT", Msg);

        cell = new TableCell();
        cell.Width = Unit.Percentage(25);
        AddCellTextToRow(row, cell, "TÊN SẢN PHẨM", Msg);

        cell = new TableCell();
        cell.Width = Unit.Percentage(40);
        AddCellTextToRow(row, cell, "ĐẶC TÍNH", Msg);

        cell = new TableCell();
        cell.Width = Unit.Percentage(12);
        AddCellTextToRow(row, cell, "ĐƠN GIÁ<BR>(VNĐ)", Msg);

        cell = new TableCell();
        cell.Width = Unit.Percentage(7);
        AddCellTextToRow(row, cell, "TG<BR>BH", Msg);

        tblMaster.Rows.Add(row);

    }

    private void AddRow()
    {

        PccMsg MsgTopic = new PccMsg();
        clsCommon clsCom = new clsCommon();
        MsgTopic.CreateFirstNode("Css", "tbl_trHeader1");

        PccMsg MsgCell = new PccMsg();
        MsgCell.CreateFirstNode("Css", "tbl_tdCell");

        clsWebShop cls = new clsWebShop();
        decimal USD = cls.GetMoney("USD");
        DataSet ds = cls.Get_ExportListPriceByCondition("");
        DataTable dtTopic = ds.Tables[0];
        DataTable dtCat = ds.Tables[1];
        DataTable dtProduct = ds.Tables[2];

        for (int i = 0; i < dtTopic.Rows.Count; i++)
        {
            DataRow[] drCat = dtCat.Select("TopicID=" + dtTopic.Rows[i]["TopicID"].ToString());
            if (drCat.Length <= 0) continue;

            int STT_Topic = i + 1;
            TableRow row;
            TableCell cell;
            row = new TableRow();
            row.Height = Unit.Pixel(30);

            cell = new TableCell();
            cell.ColumnSpan = 5;
            cell.HorizontalAlign = HorizontalAlign.Center;
            AddCellTextToRow(row, cell, "(" + STT_Topic + ") " + dtTopic.Rows[i]["TopicName"].ToString().ToUpper(), MsgTopic);
            tblMaster.Rows.Add(row);

            for (int j = 0; j < drCat.Length; j++)
            {

                DataRow[] drPD = dtProduct.Select("CatID=" + drCat[j]["CatID"].ToString());
                if (drPD.Length <= 0) continue;

                int STT_Cat = j + 1;
                row = new TableRow();
                row.Height = Unit.Pixel(30);
                cell = new TableCell();
                cell.ColumnSpan = 5;
                cell.HorizontalAlign = HorizontalAlign.Left;
                AddCellTextToRow(row, cell, drCat[j]["CatName"].ToString().ToUpper(), MsgTopic);
                tblMaster.Rows.Add(row);

                for (int k = 0; k < drPD.Length; k++)
                {
                    int STT_PD = k + 1;
                    row = new TableRow();
                    cell = new TableCell();
                    cell.HorizontalAlign = HorizontalAlign.Center;
                    AddCellTextToRow(row, cell, STT_PD.ToString(), MsgCell);

                    cell = new TableCell();
                    AddCellTextToRow(row, cell, drPD[k]["PdName"].ToString(), MsgCell);

                    cell = new TableCell();
                    string Features = drPD[k]["Features"].ToString();
                    if (Features.Length > 0)
                    {
                        AddCellHTMLToRow(row, cell, Features.Substring(0, Features.Length - 1), MsgCell);
                    }
                    else
                    {
                        AddCellTextToRow(row, cell, "", MsgCell);
                    }
                    decimal Price = 0;
                    if (drPD[k]["IsSaleOf"].ToString() == "Y")
                    {
                        Price = clsCom.ConvertToDecimal(drPD[k]["DiscountPrice"].ToString());
                        if (drPD[k]["DiscountRate"].ToString() == "USD")
                            Price = Price * USD;
                    }
                    else
                    {
                        Price = clsCom.ConvertToDecimal(drPD[k]["Price"].ToString());
                        if (drPD[k]["Rate"].ToString() == "USD")
                            Price = Price * USD;
                    }

                    cell = new TableCell();
                    cell.HorizontalAlign = HorizontalAlign.Right;
                    AddCellTextToRow(row, cell, clsCom.FormatMoney(Price.ToString()), MsgCell);

                    string Warranty = drPD[k]["Warranty"].ToString();
                    cell = new TableCell();
                    cell.HorizontalAlign = HorizontalAlign.Center;
                    AddCellTextToRow(row, cell, Warranty.Trim() != "" ? Warranty + "T" : "", MsgCell);

                    tblMaster.Rows.Add(row);
                }
            }
        }


    }

    #region Common Function
    private void AddCellTextToRow(TableRow row, TableCell cell, string Text, PccMsg Msg)
    {
        if (Msg.Query("Css") != "") cell.CssClass = Msg.Query("Css");
        cell.Text = Text;
        cell.BorderWidth = Unit.Pixel(1);
        row.Cells.Add(cell);
    }
    private void AddCellHTMLToRow(TableRow row, TableCell cell, string Text, PccMsg Msg)
    {
        Text = Server.HtmlDecode(Text);
        cell.Text = Text;
        cell.BorderWidth = Unit.Pixel(1);
        row.Cells.Add(cell);
    }
    #endregion

}
